package com.example.bleuesprit.parkAndroidClient;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.model.NaviLatLng;
import com.example.bleuesprit.parkAndroidClient.net.NetUtil;
import com.example.bleuesprit.parkAndroidClient.util.TTSController;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by bleuesprit on 2015/11/5.
 */
public class OrdersActivity extends Activity  {


    private ArrayList<HashMap<String,String>> orders;
    private ListView listView;
    private SwipeRefreshLayout swipeRefreshLayout;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x123) {
                try {
                    JSONObject jsonObject=new JSONObject(msg.getData().getString("result"));
                    int reciveOrdersCount = Integer.valueOf(jsonObject.getString("total"));
                    JSONArray receiveParksJA = new JSONArray(jsonObject.getString("ordersData"));
                    orders=new ArrayList<HashMap<String,String>>();

                    for(int i=0;i<reciveOrdersCount;i++)
                    {
                        JSONObject temp = receiveParksJA.getJSONObject(i);
                        HashMap<String,String> tempOrder=new HashMap<String,String>();
                        tempOrder.put("uuid",temp.getString("uuid"));
                        tempOrder.put("parkUUID",temp.getString("parkUUID"));
                        tempOrder.put("longitude",temp.getString("longitude"));
                        tempOrder.put("latitude",temp.getString("latitude"));
                        tempOrder.put("name",temp.getString("name"));
                        tempOrder.put("price",temp.getString("price"));
                        tempOrder.put("orderTime",temp.getString("orderTime"));
                        tempOrder.put("orderNumber",temp.getString("orderNumber"));
                        tempOrder.put("pushTime",temp.getString("pushTime"));
                        tempOrder.put("finishTime", temp.getString("finishTime").equals("NULL")?"未完成":temp.getString("finishTime"));
                        tempOrder.put("state",temp.getString("state"));

                        orders.add(tempOrder);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                listView.setAdapter(
                        new SimpleAdapter(OrdersActivity.this,orders,R.layout.orders_item,
                                new String[]{"name","price","orderTime","orderNumber","pushTime","state"},
                                new int[]{R.id.parkName,R.id.price,R.id.orderTime,R.id.orderNumber,R.id.pushTime,R.id.state}
                        )
                );


                listView.setOnItemClickListener(
                        new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Location location=MainActivity.aMap.getMyLocation();

                                // 起点终点坐标
                                NaviLatLng mNaviStart = new NaviLatLng(location.getLatitude(), location.getLongitude());

                                NaviLatLng mNaviEnd = new NaviLatLng(Double.valueOf(orders.get(position).get("latitude")), Double.valueOf(orders.get(position).get("longitude")));
                                // 起点终点列表
                                ArrayList<NaviLatLng> mStartPoints = new ArrayList<NaviLatLng>();
                                ArrayList<NaviLatLng> mEndPoints = new ArrayList<NaviLatLng>();

                                mStartPoints.add(mNaviStart);
                                mEndPoints.add(mNaviEnd);

                                mAMapNavi.calculateDriveRoute(mStartPoints,
                                        mEndPoints, null, AMapNavi.DrivingDefault);
                                Intent emulatorIntent = new Intent(OrdersActivity.this,
                                        SimpleNaviActivity.class);
                                emulatorIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                                startActivity(emulatorIntent);
                            }
                        }
                );
                swipeRefreshLayout.setRefreshing(false);
            }
        }

    };




    // 导航资源
    private AMapNavi mAMapNavi;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orders);

        listView=(ListView)findViewById(R.id.orders_listview);
        swipeRefreshLayout=(SwipeRefreshLayout)findViewById(R.id.orders_swipe);
        swipeRefreshLayout.setOnRefreshListener(new refreshListener());
        JSONObject emptyMessgae=new JSONObject();
        NetUtil.sendToServer("getAllOrders", emptyMessgae, handler);


        //语音初始化
        TTSController ttsManager = TTSController.getInstance(this);// 初始化语音模块
        ttsManager.init();


        //导航初始化
        AMapNavi.getInstance(this).setAMapNaviListener(ttsManager);// 设置语音模块播报
        mAMapNavi = AMapNavi.getInstance(this);



    }

    private class refreshListener implements OnRefreshListener
    {
        @Override
        public void onRefresh() {
            JSONObject emptyMessgae=new JSONObject();
            NetUtil.sendToServer("getAllOrders", emptyMessgae, handler);
            Log.i("OrdersActivity","onRefresh");

        }
    }


    public class ordersAdapter extends BaseAdapter
    {
        private LayoutInflater layoutInflater;

        private ViewHolder viewHolder;

        public ordersAdapter(Context context)
        {
            layoutInflater=LayoutInflater.from(context);
        }


        @Override
        public int getCount() {
            return orders.size();
        }

        @Override
        public Object getItem(int position) {
            return orders.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {


			if (convertView == null) {

				viewHolder=new ViewHolder();



				convertView = layoutInflater.inflate(R.layout.orders_item, null);
               // viewHolder.navi_but=(Button)convertView.findViewById(R.id.navi_but);
                viewHolder.orderNumber=(TextView)convertView.findViewById(R.id.orderNumber);
                viewHolder.orderTime=(TextView)convertView.findViewById(R.id.orderTime);
                viewHolder.parkName=(TextView)convertView.findViewById(R.id.parkName);
                viewHolder.price=(TextView)convertView.findViewById(R.id.price);
                viewHolder.pushTime=(TextView)convertView.findViewById(R.id.pushTime);
                viewHolder.state=(TextView)convertView.findViewById(R.id.state);
                viewHolder.finishTime=(TextView)convertView.findViewById(R.id.finishTime);
				convertView.setTag(viewHolder);
			}else {
                viewHolder = (ViewHolder)convertView.getTag();
			}

            viewHolder.state.setText(orders.get(position).get("state"));
            viewHolder.pushTime.setText(orders.get(position).get("pushTime"));
            viewHolder.orderTime.setText(orders.get(position).get("orderTime"));
            viewHolder.orderNumber.setText(orders.get(position).get("orderNumber"));
            viewHolder.price.setText(orders.get(position).get("price"));
            viewHolder.finishTime.setText(orders.get(position).get("finishTime"));
            viewHolder.parkName.setText(orders.get(position).get("name"));





			//给Button添加单击事件  添加Button之后ListView将失去焦点  需要的直接把Button的焦点去掉
           // viewHolder.navi_but.setOnClickListener( new ButtonLisener(position));



			return convertView;
        }
    }



    public class ViewHolder
    {
        public TextView parkName;
        public TextView pushTime;
        public TextView orderTime;
        public TextView orderNumber;
        public TextView finishTime;
        public TextView price;
        public TextView state;
        public Button navi_but;

    }

    public class ButtonLisener implements View.OnClickListener
    {
        private int orderPosition;
        public ButtonLisener(int orderPosition)
        {
            this.orderPosition=orderPosition;
        }

        @Override
        public void onClick(View v) {
//            Intent intent=new Intent(OrdersActivity.this,SimpleNaviActivity.class);
//            startActivity(intent);

            Toast.makeText(OrdersActivity.this,"dsfsafsfd",Toast.LENGTH_LONG).show();
        }
    }

}

